package com.ztsoft.user.utils;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.ztsoft.user.mapper.project.AnswerQuoteMapper;
import com.ztsoft.user.pojo.entity.project.AnswerQuote;
import com.ztsoft.user.pojo.vo.project.AnswerQuoteVo;
import com.ztsoft.user.service.project.AnswerQuoteService;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;

public class AnswerQuoteListener extends AnalysisEventListener<AnswerQuoteVo> {

    private final AnswerQuoteService answerQuoteService;
    private final String pid;

    public AnswerQuoteListener(AnswerQuoteService answerQuoteService, String pid) {
        this.answerQuoteService = answerQuoteService;
        this.pid = pid;
    }

    /**
     * 每隔2条存储数据库，实际使用中可以3000条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 10;
    List<AnswerQuote> list = new ArrayList<>();

    @Override
    public void invoke(AnswerQuoteVo answerQuoteVo, AnalysisContext analysisContext) {
        AnswerQuote answerQuote = new AnswerQuote();
        BeanUtils.copyProperties(answerQuoteVo, answerQuote);
        answerQuote.setPid(pid);
        list.add(answerQuote);
        // 达到BATCH_COUNT了，需要去存储一次数据库，防止数据几万条数据在内存，容易OOM
        if (list.size() >= BATCH_COUNT) {
            saveData(); // 调用下面的持久化方法
            // 存储完成清理 list
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData();

    }

    /**
     * 存储数据库
     */
    private void saveData() {
        answerQuoteService.saveBatch(list);
    }

}